//
//  ShoppingCartHomeViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/7/18.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "ShoppingCartHomeViewController.h"
#import "ShopcartModel.h"
#import "ShopcartHomeTableViewCell.h"
#import "ShopcartOrderViewController.h"
#import "GoodStandardView.h"
#import "GoodsDetailViewController.h"
#import "SKUManager.h"
#import "ShopcartTableHeaderView.h"
#import "ScrapeUpViewController.h"

typedef NS_ENUM(NSUInteger, NetWorkType) {
    NetWorkTypeHearder,
    NetWorkTypeFooter,
    NetWorkTypeOther,
};

@interface ShoppingCartHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *submitButton;
@property (weak, nonatomic) IBOutlet UIView *noDataView;
@property (weak, nonatomic) IBOutlet UIButton *noDataButton;
@property (weak, nonatomic) IBOutlet UIButton *selectAllButton;

@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) NSMutableArray<ShopcartClassifyModel *> *tableArray;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) NSMutableArray<ShopcartModel *> *selectArray;
@property (nonatomic, strong) NSMutableArray<ShopcartModel *> *editArray;

@property (nonatomic, strong) UITextField *editField;

@end


@implementation ShoppingCartHomeViewController
#pragma mark - Get
- (NSMutableArray<ShopcartClassifyModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
- (NSMutableArray<ShopcartModel *> *)selectArray {
    if (!_selectArray) {
        _selectArray = [[NSMutableArray alloc] init];
    }
    return _selectArray;
}
- (NSMutableArray<ShopcartModel *> *)editArray {
    if (!_editArray) {
        _editArray = [[NSMutableArray alloc] init];
    }
    return _editArray;
}
- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setTitle:@"编辑" forState:UIControlStateNormal];
        [_rightButton setTitle:@"完成" forState:UIControlStateSelected];
        [_rightButton setTitleColor:[UIColor colorWithHex:0x030303 alpha:1.0f] forState:UIControlStateNormal];
        [_rightButton.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
        [_rightButton addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setFrame:CGRectMake(0, 0, 35, 30)];
    }
    return _rightButton;
}
#pragma mark - IBAction
- (IBAction)selectAllButtonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
    if (button.selected) {
        [self.selectArray removeAllObjects];
        for (ShopcartClassifyModel *listModel in self.tableArray) {
            for (ShopcartModel *model in listModel.shopcart) {
                model.isSelect = YES;
                [self.selectArray addObject:model];
            }
        }
        [self.tableView reloadData];
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    } else {
        for (ShopcartModel *model in self.selectArray) {
            model.isSelect = NO;
        }
        [self.selectArray removeAllObjects];
        [self.tableView reloadData];
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    [self updateBottomView];
}
- (IBAction)submitButtonAction:(id)sender {
    if (self.selectArray.count == 0) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"您还没有选择商品哦" animated:YES];
        return;
    }
    
    if (self.rightButton.selected) {
        // 删除选中的商品
        __block typeof(self) blockSelf = self;
        [self showAlertWithTitleArray:@[@"取消",@"删除"] title:@"温馨提示" message:@"确认删除选中商品？" alertStyle:UIAlertControllerStyleAlert];
        self.alertBlock = ^(NSString *actionTitle) {
            if ([actionTitle isEqualToString:@"删除"]) {
                [blockSelf removeObjectFromEditArray:blockSelf.selectArray];
                [blockSelf deleteGoods:[blockSelf getScids]];
            }
        };
    } else {
        for (ShopcartModel *tempModel in self.selectArray) {
            if ([tempModel isKindOfClass:[ShopcartModel class]] && tempModel.gprice.doubleValue == 0) {
                [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"您所要结算的商品中包含没有库存的商品，请重新选择" animated:YES];
                return;
            }
        }
        
        ShopcartOrderViewController *orderVC = [[ShopcartOrderViewController alloc] init];
        // 选中商品
        NSMutableArray<ShopcartClassifyModel *> *tempArr = [ShopcartClassifyModel mj_objectArrayWithKeyValuesArray:self.tableArray];
        for (ShopcartClassifyModel *listModel in tempArr) {
            [listModel.shopcart removeAllObjects];
        }
        
        for (NSInteger i = 0; i < self.tableArray.count; i++) {
            ShopcartClassifyModel *listModel = self.tableArray[i];
            for (NSInteger j = 0; j < listModel.shopcart.count; j++) {
                ShopcartModel *model = listModel.shopcart[j];
                if (model.isSelect) {
                    [tempArr[i].shopcart addObject:model];
                }
            }
        }
        for (ShopcartClassifyModel *listModel in tempArr.reverseObjectEnumerator) {
            if (listModel.shopcart.count == 0) {
                [tempArr removeObject:listModel];
            }
        }
        
        orderVC.tableArray = tempArr;
//        orderVC.priceAttStr = [[self.totalPriceLabel.text componentsSeparatedByString:@"¥"] lastObject];
        orderVC.type = ShopcartOrderTypeCart;
        //MARK:测试
        orderVC.isHaveWorldwide = NO;
        [self.navigationController pushViewController:orderVC animated:YES];
    }
}
- (IBAction)noDateButtonAction:(id)sender {
    // 去逛逛
    [self.navigationController popToRootViewControllerAnimated:NO];
    BaseTabbarViewController *tabbarVC = (BaseTabbarViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [tabbarVC setSelectedIndex:0];
}

#pragma mark - viewController
//static NSInteger BaseTextFieldTag = 100;
static NSString *shopcartHomeTableIdentifier = @"shopcartHomeTableIdentifier";
- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"购物车";
    [self.view setBackgroundColor:[UIColor backgroundColor]];
    
    [self hiddenShadowImage:NO];
    if (self.type != 1) {
        self.navigationItem.leftBarButtonItem = nil;
    }
    
    [self createTableView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![UserInfo shareInstance].isLogin) {
        [self.tableArray removeAllObjects];
        [self createNavBar];
        [self.tableView reloadData];
        [self updateBottomView];
        [self.noDataView setHidden:NO];
        return;
    }
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self.rightButton setSelected:NO];
    
    [self getNetData:NetWorkTypeOther];
    [self.selectArray removeAllObjects];
    [self.selectAllButton setSelected:NO];
    [self updateBottomView];
}

#pragma mark - action
- (void)keyboardWillShow:(NSNotification *)notification {
    [super keyboardWillShow:notification];
    if (self.editField) {
        CGRect textFieldR = [self.editField.superview convertRect:self.editField.frame toView:[UIApplication sharedApplication].keyWindow];
        CGFloat sub = textFieldR.origin.y+textFieldR.size.height - _keyboardEndFrame.origin.y;
        if (sub > 0) {
            [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y+sub+53) animated:YES];
        }
    }
}
- (void)keyboardWillHide:(NSNotification *)notification {
    [super keyboardWillHide:notification];
    if (self.tableView.contentSize.height < self.tableView.height) {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else if ((self.tableView.contentOffset.y+self.tableView.height) > self.tableView.contentSize.height) {
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height-self.tableView.height) animated:YES];
    }
}
- (void)createNavBar {
//    //MARK: 测试
//    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
//    self.navigationItem.rightBarButtonItem = right;
//    return;
//    //MARK:-
    
    if (self.tableArray.count > 0) {
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
        self.navigationItem.rightBarButtonItem = right;
    } else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}
- (void)rightBarButtonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
//    [self.tableView reloadData];
    if (!button.selected && self.editArray.count > 0) {
        [self editShopcart:[self getEditDic]];
    } else {
        NSMutableIndexSet *indexs = [NSMutableIndexSet indexSet];
        for (NSInteger i = 0; i < self.tableArray.count; i++) {
            [indexs addIndex:i];
        }
        [self.tableView reloadSections:indexs withRowAnimation:UITableViewRowAnimationFade];
        [self updateBottomView];
    }
//    if (button.selected) {
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
//        [self updateBottomView];
//    } else {
//        if (self.editArray.count > 0) {
//            [self editShopcart:[self getEditDic]];
//        } else {
//            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
//            [self updateBottomView];
//        }
//    }
    
}
- (void)createTableView {
    self.page = 1;
    [self.tableView registerNib:[UINib nibWithNibName:@"ShopcartHomeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:shopcartHomeTableIdentifier];
    [self.tableView clearExtendCellLine];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self.selectArray removeAllObjects];
        [self getNetData:NetWorkTypeHearder];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getNetData:NetWorkTypeFooter];
    }];
    [self.tableView.mj_footer setHidden:YES];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    //[(AppDelegate *)[UIApplication sharedApplication].delegate updateBadgeValue:0];
    if (_page != 1) {
        _page--;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics type:(NetWorkType)type{
    //[(AppDelegate *)[UIApplication sharedApplication].delegate updateBadgeValue:[dics[@"totalRow"] integerValue]];
    
    if (self.page == 1) {
        [self.tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *arr = dics[@"list"];
    if (arr.count == 0 && self.page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dataDic in arr) {
        ShopcartClassifyModel *model = [ShopcartClassifyModel mj_objectWithKeyValues:dataDic];
        [self.tableArray addObject:model];
    }
    
    if ([dics[@"totalRow"] integerValue] > self.tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (self.tableArray.count > 0) {
        [self.noDataView setHidden:YES];
    } else {
        [self.noDataView setHidden:NO];
    }
    
    [self createNavBar];
    [self updateBottomView];
   
    [self.tableView reloadData];
//    if (type == NetWorkTypeFooter) {
//        [self.tableView reloadData];
//    } else {
//        NSMutableIndexSet *sectionSet = [[NSMutableIndexSet alloc] init];
//        for (NSInteger i = 0; i < self.tableArray.count; i++) {
//            [sectionSet addIndex:i];
//        }
//        // 适配iOS11
//        if (@available(iOS 11.0, *)) {
//            [self.tableView performBatchUpdates:^{
//                [self.tableView reloadSections:sectionSet withRowAnimation:UITableViewRowAnimationFade];
//            } completion:^(BOOL finished) {
//                
//            }];
//        } else {
//            [self.tableView beginUpdates];
//            [self.tableView reloadSections:sectionSet withRowAnimation:UITableViewRowAnimationFade];
//            [self.tableView endUpdates];
//        }
//    }
}
- (void)updateBottomView {
    //MARK:测试 总价，优惠价钱
    double total = 0, subTotal = 0;
//    for (ShopcartModel *model in self.selectArray) {
//        total += (model.gprice.floatValue * model.number.integerValue);
//    }
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartClassifyModel *listModel = self.tableArray[i];
        double classTotal = 0, classSubTotal = 0;
        for (NSInteger j = 0; j < listModel.shopcart.count; j++) {
            ShopcartModel *model = listModel.shopcart[j];
            if (model.isSelect) {
                classTotal += (model.gprice.doubleValue * model.number.integerValue);
            }
        }
        for (GoodsFullCut *cutModel in listModel.fullcut) {
            if (classTotal > cutModel.fcfull.doubleValue) {
                classSubTotal = cutModel.fccut.doubleValue;
                break;
            }
        }
        total += classTotal;
        subTotal += classSubTotal;
    }
    
    
    if (self.rightButton.selected) {
        // 编辑
        [self.submitButton setTitle:@"全部删除" forState:UIControlStateNormal];
        
//        NSString *totalPriceStr = [NSString stringWithFormat:@"合计：¥%.2f\n总额:¥%.2f 立减:¥%.2f",total-subTotal,total,subTotal];
//        NSMutableAttributedString *totalAttStr = [[NSMutableAttributedString alloc] initWithString:totalPriceStr];
//        [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(14),
//                                     NSForegroundColorAttributeName:[UIColor blackTextColor]} range:NSMakeRange(0, 3)];
//        [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangMediumFontSize(16),
//                                     NSForegroundColorAttributeName:[UIColor blackTextColor]} range:[totalPriceStr rangeOfString:[NSString stringWithFormat:@"¥%.2f",total-subTotal]]];
//        [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(10),
//                                     NSForegroundColorAttributeName:[UIColor blackTextColor]} range:[totalPriceStr rangeOfString:[NSString stringWithFormat:@"总额:¥%.2f 立减:¥%.2f",total,subTotal]]];
//        // 行间距
//        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//        paragraphStyle.lineSpacing = 0;
//        paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
//        [totalAttStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, totalPriceStr.length)];
//        
//        [self.totalPriceLabel setAttributedText:totalAttStr];
//        [self.totalPriceLabel setTextAlignment:NSTextAlignmentLeft];
        
    } else {
        // 完成
        // 数量
        NSString *countStr = @"结算";
        if (self.selectArray.count > 0) {
            countStr = [NSString stringWithFormat:@"结算(%ld)",[self getSelectGoodsNumber]];
        }
        [self.submitButton setTitle:countStr forState:UIControlStateNormal];
        
//        NSString *totalPriceStr = [NSString stringWithFormat:@"合计：¥%.2f",total-subTotal];
//        NSMutableAttributedString *totalAttStr = [[NSMutableAttributedString alloc] initWithString:totalPriceStr];
//        [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(16),
//                                     NSForegroundColorAttributeName:[UIColor ThemeColor]} range:NSMakeRange(0, totalPriceStr.length)];
//        [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(14),
//                                     NSForegroundColorAttributeName:[UIColor blackTextColor]} range:NSMakeRange(0, 3)];
//        // 行间距
//        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//        paragraphStyle.lineSpacing = 0;
//        paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
//        [totalAttStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, totalPriceStr.length)];
//
//        [self.totalPriceLabel setAttributedText:totalAttStr];
//        [self.totalPriceLabel setTextAlignment:NSTextAlignmentRight];
    }
    NSString *totalText = [[NSString stringWithFormat:@"¥%.2f",total-subTotal] replacePriceSuffix];
    NSString *allText = [[NSString stringWithFormat:@"¥%.2f",total] replacePriceSuffix];
    NSString *subTotalText = [[NSString stringWithFormat:@"¥%.2f",subTotal] replacePriceSuffix];
    NSString *totalPriceStr = [NSString stringWithFormat:@"合计:%@\n总额:%@ 立减:%@",totalText,allText,subTotalText];
    
    NSMutableAttributedString *totalAttStr = [[NSMutableAttributedString alloc] initWithString:totalPriceStr];
    [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(14),
                                 NSForegroundColorAttributeName:[UIColor blackTextColor]} range:NSMakeRange(0, 3)];
    [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangMediumFontSize(16),
                                 NSForegroundColorAttributeName:[UIColor blackTextColor]} range:[totalPriceStr rangeOfString:totalText]];
    [totalAttStr setAttributes:@{NSFontAttributeName:TextPingFangFontSize(10),
                                 NSForegroundColorAttributeName:[UIColor blackTextColor]} range:[totalPriceStr rangeOfString:[NSString stringWithFormat:@"总额:%@ 立减:%@",allText,subTotalText]]];
    // 行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 0;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    [totalAttStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, totalPriceStr.length)];
    
    [self.totalPriceLabel setAttributedText:totalAttStr];
    [self.totalPriceLabel setTextAlignment:NSTextAlignmentLeft];
    
    
    
    NSInteger goodsCount = [self getAllGoodsCount];
    if (self.selectArray.count == goodsCount && goodsCount > 0) {
        [self.selectAllButton setSelected:YES];
    } else {
        [self.selectAllButton setSelected:NO];
    }
}
- (void)addEditArrayObject:(ShopcartModel *)object type:(EditType)type {
    if (type == EditTypeSpecs) {
        [GoodStandardView showGoodStandardViewWithTitle:object.gname
                                                  price:object.gprice
                                                pgprice:@""
                                                  count:object.number
                                               imageURL:object.gimg
                                  goodAttributeModelArr:[SKUManager getSelectOriginDataArr:object.attribute withPriceSkuArr:object.goodsattribute withGaid:object.gaid]
                            goodsAttributePriceModelArr:object.goodsattribute
                                                   type:GoodStandardViewTypeEditCart
                                              needReset:NO
                                                  block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
                                                      
                                                      if (![object.gaid isEqualToString:priceModel.gaid] || ![object.number isEqualToString:count]) {
                                                          
                                                          object.gaid = priceModel.gaid;
                                                          object.number = count;
                                                          
                                                          for (ShopcartModel *model in self.editArray) {
                                                              if ([model.scid isEqualToString:object.scid]) {
                                                                  [self.editArray removeObject:model];
                                                                  break;
                                                              }
                                                          }
                                                          [self.editArray addObject:object];
                                                          [self.tableView reloadData];
                                                      }
                                                  }];
    } else {
        for (ShopcartModel *model in self.editArray) {
            if ([model.scid isEqualToString:object.scid]) {
                [self.editArray removeObject:model];
                break;
            }
        }
        [self.editArray addObject:object];
    }
    
}
- (void)removeObjectFromEditArray:(NSArray *)array {
    for (ShopcartModel *model in array) {
        for (ShopcartModel *editModel in self.editArray) {
            if ([editModel.scid isEqualToString:model.scid]) {
                [self.editArray removeObject:editModel];
                break;
            }
        }
    }
}
- (NSInteger)getAllGoodsCount {
    NSInteger goodsCount = 0;
    for (ShopcartClassifyModel *listModel in self.tableArray) {
        goodsCount += listModel.shopcart.count;
    }
    return goodsCount;
}
- (NSInteger)getSelectGoodsNumber {
    NSInteger goodsNumber = 0;
    for (ShopcartModel *model in self.selectArray) {
        goodsNumber += model.number.integerValue;
    }
    return goodsNumber;
}
- (NSInteger)getStock:(ShopcartModel *)model {
    for (GoodsAttributePriceModel *goodsAttPModel in model.goodsattribute) {
        if ([model.gaid isEqualToString:goodsAttPModel.gaid]) {
            return goodsAttPModel.gastock.integerValue;
        }
    }
    return 0;
}
- (NSString *)getScids {
    NSString *scids;
    for (NSInteger i = 0; i < self.selectArray.count; i++) {
        ShopcartModel *model = self.selectArray[i];
        if (i == 0) {
            scids = model.scid;
        } else {
            scids = [NSString stringWithFormat:@"%@,%@",scids,model.scid];
        }
    }
    
    return scids;
}
- (NSMutableDictionary *)getEditDic {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    NSString *scids = @"", *gaids = @"", *numbers = @"";
    for (NSInteger i = 0; i < self.editArray.count; i++) {
        ShopcartModel *model = self.editArray[i];
        if (i == 0) {
            scids = model.scid;
            gaids = model.gaid;
            numbers = model.number;
        } else {
            scids = [NSString stringWithFormat:@"%@,%@",scids,model.scid];
            gaids = [NSString stringWithFormat:@"%@,%@",gaids,model.gaid];
            numbers = [NSString stringWithFormat:@"%@,%@",numbers,model.number];
        }
    }
    [dic setObject:scids forKey:@"scids"];
    [dic setObject:gaids forKey:@"gaids"];
    [dic setObject:numbers forKey:@"numbers"];
    return dic;
}
#pragma mark - 网络请求
- (void)getNetData:(NetWorkType)type {
    NSDictionary *dic = @{@"pageNumber":@(_page),@"pageSize":@"1000"};
    [MYAFNetworking POST:URL_Get_Shopcart parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject[@"data"];
            [self getNetSuccess:dics type:type];
        } else {
            if ([responseObject[@"code"] isEqualToString:@"204"]) {
                [self.tableArray removeAllObjects];
                [self createNavBar];
                [self.tableView reloadData];
                [self updateBottomView];
                [self.noDataView setHidden:NO];
            }
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            [self getNetFailure];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
        [self getNetFailure];
    }];
}
- (void)deleteGoods:(NSString *)scids {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Delete_Shopcart parameters:@{@"scids":scids} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
//            for (NSString *scid in [scids componentsSeparatedByString:@","]) {
//                for (ShopcartModel *model in self.selectArray) {
//                    if ([model.scid isEqualToString:scid]) {
//                        [self.selectArray removeObject:model];
//                        break;
//                    }
//                }
////                for (ShopcartModel *model in self.tableArray) {
////                    if ([model.scid isEqualToString:scid]) {
////                        [self.tableArray removeObject:model];
////                        break;
////                    }
////                }
//            }
            [self getNetData:NetWorkTypeOther];
//            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
//            if (self.tableArray.count > 0) {
//                [self.noDataView setHidden:YES];
//            } else {
//                [self.noDataView setHidden:NO];
//            }
//            [self createNavBar];
//            [self updateBottomView];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)editShopcart:(NSMutableDictionary *)dic {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Update_Shopcart parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [self.editArray removeAllObjects];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
            [self updateBottomView];
        } else {
            [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
            [self.rightButton setSelected:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
        [self.rightButton setSelected:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.tableArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray[section].shopcart.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ShopcartClassifyModel *listModel = self.tableArray[indexPath.section];
    ShopcartModel *model = listModel.shopcart[indexPath.row];
    ShopcartHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:shopcartHomeTableIdentifier forIndexPath:indexPath];
    
    [cell updateCellWithModel:model];
    if (indexPath.row == listModel.shopcart.count-1) {
        [cell.lineView setHidden:YES];
    } else {
        [cell.lineView setHidden:NO];
    }
    cell.editCountTextField.indexPath = indexPath;
    //[cell.editCountTextField setTag:indexPath.row+BaseTextFieldTag];
    [cell.editCountTextField setDelegate:self];
    
    if (self.rightButton.selected) {
        // 编辑
        [cell.normalView setHidden:YES];
        [cell.editView setHidden:NO];
    } else {
        // 完成
        [cell.normalView setHidden:NO];
        [cell.editView setHidden:YES];
    }
    __block typeof(cell) blockCell = cell;
    cell.editBlock = ^(EditType type) {
        switch (type) {
            case EditTypeSub:
            {
                NSInteger count = blockCell.editCountTextField.text.integerValue-1;
                if (count < 1) {
                    count = 1;
                    return;
                }
                model.number = [NSString stringWithFormat:@"%ld",count];
                [blockCell.editCountTextField setText:[NSString stringWithFormat:@"%ld",count]];
                
                [self addEditArrayObject:model type:EditTypeSub];
                break;
            }
            case EditTypeAdd:
            {
                NSInteger stock = [self getStock:model];
                NSInteger count = blockCell.editCountTextField.text.integerValue+1;
                if (count > stock) {
                    count = stock;
                    [MBProgressHUD myShowHUDAddedTo:[UIApplication sharedApplication].keyWindow labelText:@"数量超出库存~" animated:YES];
                    return;
                }
                model.number = [NSString stringWithFormat:@"%ld",count];
                [blockCell.editCountTextField setText:[NSString stringWithFormat:@"%ld",count]];
                
                [self addEditArrayObject:model type:EditTypeAdd];
                break;
            }
            case EditTypeSpecs:
            {
                // 选择规格
                [self addEditArrayObject:model type:EditTypeSpecs];
                break;
            }
            case EditTypeDelete:
            {
                __block typeof(self) blockSelf = self;
                [self showAlertWithTitleArray:@[@"取消",@"删除"] title:@"温馨提示" message:@"确认删除该商品？" alertStyle:UIAlertControllerStyleAlert];
                self.alertBlock = ^(NSString *actionTitle) {
                    if ([actionTitle isEqualToString:@"删除"]) {
                        [blockSelf removeObjectFromEditArray:@[model]];
                        [blockSelf deleteGoods:model.scid];
                    }
                };
                break;
            }
            case EditTypeSelect:
            {
                model.isSelect = blockCell.selectButton.selected;
                if (model.isSelect) {
                    [self.selectArray addObject:model];
                } else {
                    [self.selectArray removeObject:model];
                }
                [self updateBottomView];
                break;
            }
            case EditTypeTextField:
            {
//                NSInteger count = blockCell.editCountTextField.text.integerValue;
//                if (count > model.gastock.integerValue) {
//                    count = model.gastock.integerValue;
//                    [MBProgressHUD myShowHUDAddedTo:[UIApplication sharedApplication].keyWindow labelText:@"数量超出库存~" animated:YES];
//                    return;
//                }
                break;
            }
            default:
                break;
        }
    };
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.rightButton.selected) {
        ShopcartClassifyModel *listModel = self.tableArray[indexPath.section];
        ShopcartModel *model = listModel.shopcart[indexPath.row];
        if (!model.isshelves) {
            [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
            return;
        }
        GoodsDetailViewController *goodVC = [[GoodsDetailViewController alloc] init];
        goodVC.gid = model.gid;
        goodVC.type = GoodsDetailViewControllerTypeForNormal;
        [self.navigationController pushViewController:goodVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 37;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ShopcartClassifyModel *classifyModel = self.tableArray[section];
    
    __block typeof(self) blockSelf = self;
    ShopcartTableHeaderView *view = [[ShopcartTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 37)];
    [view setBackgroundColor:[UIColor backgroundColor]];
    [view.scrapeButton setEnabled:!self.rightButton.selected];
    view.scrapeBlock = ^{
        ScrapeUpViewController * scrapeVC = [[ScrapeUpViewController alloc] init];
        scrapeVC.gcid = classifyModel.gcid;
        [blockSelf.navigationController pushViewController:scrapeVC animated:YES];
    };
    
    return view;
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.editField = textField;
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.editField == textField) {
        NSIndexPath *indexPath = ((IndexPathTextField *)textField).indexPath;
        ShopcartClassifyModel *listModel = self.tableArray[indexPath.section];
        ShopcartModel *model = listModel.shopcart[indexPath.row];
        NSInteger stock = [self getStock:model];
        if (stock > 0) {
            if (textField.text.integerValue==0) {
                textField.text = @"1";
            }
        } else {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"库存不足" animated:YES];
        }
        model.number = textField.text;
        [self addEditArrayObject:model type:EditTypeTextField];
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
